package com.itcoon.cloud.framework.ex.exception;

import com.itcoon.cloud.framework.ex.errorcode.CommonServiceErrorCode;
import com.itcoon.cloud.framework.ex.errorcode.IErrorCode;
import com.itcoon.cloud.framework.ex.errorcode.IServiceErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

public class BaseServiceException extends BaseException {

    private static final Logger log = LoggerFactory.getLogger(BaseServiceException.class);

    private IErrorCode errorCode;

    private String[] args;

    public <EX extends BaseServiceException> BaseServiceException(IServiceErrorCode<EX> errorCode, String... args){
        this(errorCode, null,  args);
    }

    public <EX extends BaseServiceException> BaseServiceException(IServiceErrorCode<EX> errorCode, Throwable cause, String... args){
        super(cause);
        this.errorCode = errorCode;
        this.args = args;

    }

    public BaseServiceException(String localizeMessage, Throwable cause, String... args){
        super(cause, localizeMessage);
        this.args = args;
    }

    public IErrorCode getErrorCode() {
        return errorCode;
    }

    public String[] getArgs() {
        return args;
    }

    public void setArgs(String[] args) {
        this.args = args;
    }

    public String getCode(){
        return this.errorCode == null ? CommonServiceErrorCode.DEFAULT_SERVICE_EXCEPTION.getCode() : errorCode.getCode();
    }

    @Override
    public void log() {
        String message = this.errorCode == null ? this.getLocalizedMessage() : this.errorCode.getMessage();
        log.error(message);
        StackTraceElement[] stackTraces = this.getStackTrace();
        int min = Math.min(10, stackTraces.length);
        this.setStackTrace(Arrays.copyOf(stackTraces, min));
        this.printStackTrace();
        Throwable subCause = this.getCause();
        if(subCause != null){
            if(subCause instanceof BaseException){
                BaseException baseException = (BaseException) subCause;
                baseException.log();
            }else{
                log.error(subCause.getLocalizedMessage(), subCause);
            }
        }
    }
}
